const { defineConfig } = require('@vue/cli-service');
const path = require('path');
const { wrapperEnv, getAppEnvConfig, createProxy } = require('./src/renderer/build/env');

function resolve(dir) {
  return path.join(__dirname, dir);
}

const env = getAppEnvConfig();
const vueEnv = wrapperEnv(env);
const { VUE_APP_PORT, VUE_APP_PROXY } = vueEnv;
const isProd = process.env.NODE_ENV === 'production';
const isReport = process.argv.includes('--report');

// 预览打包后的文件大小与分布
function previewBuild() {
  const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
  return new BundleAnalyzerPlugin();
}

function openGzip() {
  const CompressionWebpackPlugin = require('compression-webpack-plugin');
  return new CompressionWebpackPlugin({
    // 此处为新版写法
    filename: '[path][base].gz',
    threshold: 10240,
    minRatio: 0.8,
    test: new RegExp('\\.(' + ['js', 'css'].join('|') + ')$'),
    deleteOriginalAssets: false,
  });
}

const handleSvgIcon = config => {
  // 排除默认的svgloader对'src/assets/svg-icons'目录下的文件处理
  config.module.rule('svg').exclude.add(resolve('src/renderer/assets/svg-icons')).end();

  config.module
    .rule('icons')
    .test(/\.svg$/)
    .include.add(resolve('src/renderer/assets/svg-icons'))
    .end()
    .use('svg-sprite-loader')
    .loader('svg-sprite-loader')
    .options({
      symbolId: 'custom-icon-[name]',
    })
    .end()
    .before('svg-sprite-loader')
    .use('svgo-loader')
    .loader('svgo-loader')
    // 对 svg sprite的一些设置 -> svgo
    .options({
      plugins: [
        {
          name: 'preset-default',
          params: {
            // 覆写默认插件配置
            overrides: {},
          },
        },
        {
          name: 'removeAttrs',
          params: {
            attrs: '(fill|fill-rule|clip-rule)',
          },
        },
        {
          name: 'addAttributesToSVGElement',
          params: {
            attributes: [{ fill: 'currentColor' }],
          },
        },
      ],
    });
};

console.log(createProxy(VUE_APP_PROXY));

module.exports = defineConfig({
  transpileDependencies: false,
  productionSourceMap: false,
  runtimeCompiler: false,
  devServer: {
    port: VUE_APP_PORT,
    open: false,
    hot: false,
    headers: {
      'Access-Control-Allow-Origin': '*',
      'Access-Control-Allow-Methods': '*',
      'Access-Control-Allow-Headers': '*',
    },
    // proxy: createProxy(VUE_APP_PROXY),
  },
  css: {
    extract: isProd,
    sourceMap: !isProd,
    loaderOptions: {
      less: {
        lessOptions: {
          modifyVars: {},
          javascriptEnabled: true,
        },
      },
    },
  },
  chainWebpack(config) {
    config.plugins.delete('prefetch');
    // config.plugins.delete('preload');

    // 修复HMR (热更新不起作用可开启)
    config.resolve.symlinks(true);

    handleSvgIcon(config);

    // 移除pug loader，如果需要使用pug模板语法请移除
    config.module.rules.delete('pug');

    // 移除sass的支持（需要使用sass时请移除）
    config.module.rules.delete('scss');
    config.module.rules.delete('sass');

    // 移除stylus的支持（需要使用stylus时请移除）
    config.module.rules.delete('stylus');

    // 忽略解析markdown文件
    config.module.noParse(/\.md$/);

    if (isProd) {
      config.optimization.minimize(true);
    } else {
      config.optimization.minimize(false);
      config.devtool('source-map');
    }
  },
  configureWebpack() {
    const config = {
      entry: './src/renderer/main.js',
      resolve: {
        // fallback: {
        //   crypto: false,
        //   fs: false,
        //   path: false,
        // },
        alias: {
          '@': resolve('./src/renderer'),
          $main: resolve('./src/main'),
          $lib: resolve('./src/lib'),
        },
      },
      plugins: [],
    };
    if (isProd) {
      config.plugins.push(openGzip());

      /**
       * optimization.chunkIds: webpack5中的默认配置已是最优，无需修改
       */
      config.optimization = {
        // https://webpack.docschina.org/configuration/optimization/#optimizationruntimechunk
        runtimeChunk: {
          name: 'webpack-runtime',
        },
        splitChunks: {
          cacheGroups: {
            libs: {
              name: 'chunk-vendor',
              chunks: 'initial',
              minChunks: 1,
              test: /[\\/]node_modules[\\/]/,
              priority: 1,
              reuseExistingChunk: true,
              enforce: true,
            },
            common: {
              name: 'chunk-common',
              chunks: 'initial',
              minChunks: 2,
              maxInitialRequests: 5,
              minSize: 0,
              priority: 2,
              reuseExistingChunk: true,
              enforce: true,
            },
            index: {
              name: 'chunk-index',
              chunks: 'all',
              minChunks: 1,
              test: /[\\/]node_modules[\\/](sortablejs|screenfull|nprogress|hotkeys-js|fuse\.js|better-scroll|lowdb|shortid)[\\/]/,
              priority: 3,
              reuseExistingChunk: true,
              enforce: true,
            },
            vue: {
              name: 'chunk-vue',
              test: /[\\/]node_modules[\\/](vue|vue-router|pinia|@vueuse\/core|@vue\/shared)[\\/]/,
              chunks: 'all',
              priority: 3,
              reuseExistingChunk: true,
              enforce: true,
            },
            antv: {
              name: 'chunk-antv',
              test: /[\\/]node_modules[\\/](ant-design-vue|@ant-design)[\\/]/,
              chunks: 'all',
              priority: 3,
              reuseExistingChunk: true,
              enforce: true,
            },
          },
        },
      };

      if (isReport) {
        config.plugins.push(previewBuild());
      }
    }
    return config;
  },
  pluginOptions: {
    electronBuilder: {
      nodeIntegration: true,
      builderOptions: {},
      outputDir: 'dist/electron',
      // 主进程入口文件
      mainProcessFile: 'src/main/main.js',
      mainProcessWatch: ['src/main'],
      preload: {
        workbenchApplicationWindowPreload: 'src/main/preload/workbenchApplicationWindowPreload.js',
        viewPreload: 'src/main/view-preload.js',
        multipleTabPreload: 'src/main/workbench-application/multiple-tab-preload.js',
      },
      chainWebpackMainProcess(config) {
        config.devtool('source-map');
      },
    },
  },
  // pages: {
  //   workbenchApplication: {
  //     entry: 'src/applications/renderer/klasse-cloud/main.js',
  //     template: 'src/applications/renderer/klasse-cloud/index.html',
  //     filename: 'klasse-cloud.html',
  //     chunks: ['klasseCloud'],
  //     title: '泉城e学',
  //   },
  // }
});
